<?php
namespace App\Http\Logic;


use App\Events\UserRegisterEvent;
use App\Exceptions\InvalidRequestException;
use App\Models\User;
use App\Models\UserQq;
use App\Models\UserWeixin;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Laravel\Socialite\Facades\Socialite;

class LoginLogic extends BaseLogic
{
	public function __construct()
	{
		# code...
	}

    /**
     * 登录 （用户名密码-手机号）
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     */
	public function login($request)
    {
        // 用户名密码登录
        if ($request['type'] == User::LOGIN_TYPE_ACCOUNT) {
            if (! $token = auth()->attempt(['username' => $request['username'], 'password' => $request['password']] )) {
                $this->throwNewInvalidException('用户名密码不正确', 401);
            }
            return $this->getTokenInfo($token);
        }

        // 手机号登录
        if ($request['type'] == User::LOGIN_TYPE_PHONE) {

        }
        return false;
    }

    /**
     * 第三方登录
     * @param $type
     * @return array
     * @throws InvalidRequestException
     * @throws \Throwable
     */
    public function socialLogin($type)
    {
        $social = Socialite::driver($type)->user();

        switch ($type) {
            case 'qq':
                // 查找是否已经注册
                $user = UserQq::model()->simpleFindOne(['openid'=> $social->user['openid']]);
                break;
            case 'weixin':
                $user = UserWeixin::model()->simpleFindOne(['openid'=> $social->user['openid']]);
                break;
            default :
                $this->throwNewInvalidException('暂不提供此方式登录', 403);
        }

        if (empty($user)) {
            DB::beginTransaction();
            try {
                $user = User::create(['created_date' => date('Ymd')]);

                // 执行新注册用户的事件
                event(new UserRegisterEvent($user));

                if ($type == 'qq') {
                    $user->userQq()->create([
                        'nickname' => $social->user['nickname'],
                        'avatar' => $social->user['headimgurl'],
                        'openid' => $social->user['openid']
                    ]);
                    DB::commit();
                }
                if ($type == 'weixin') {
                    $user->userWeixin()->create([
                        'nickname' => $social->user['nickname'],
                        'avatar' => $social->user['headimgurl'],
                        'openid' => $social->user['openid']
                    ]);
                    DB::commit();
                }
            } catch (\Exception $e) {
                DB::rollBack();
                throw new \Exception($e->getMessage());
            }
        } else {
            $user = $user->user;
            if ($user->status == User::USER_STATUS_FORBIDDEN) {
                $this->throwNewInvalidException('您的账号已被限制登录,请联系管理员...', 403);
            }
        }

        $token = auth('api')->login($user);
        return $this->getTokenInfo($token);
    }

    public function refreshToken()
    {
        $token = auth('api')->refresh();
        return $this->getTokenInfo($token);
    }

    public function logout()
    {
        return auth('api')->logout();
    }

    protected function getTokenInfo($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ];
    }
}
